extends Node

@onready var sfx_hover = $SFX_Hover
@onready var sfx_click = $SFX_Click

func _ready() -> void:
	#监听未来添加的节点
	get_tree().node_added.connect(_on_node_added)
	
	#遍历所有已经存在的节点 (查缺补漏)
	var root = get_tree().root
	_connect_recursively(root)

#递归查找函数的辅助函数
func _connect_recursively(node: Node):
	# 如果是按钮，就连接
	if node is BaseButton:
		_connect_button(node)
	
	#继续查找它的子节点
	for child in node.get_children():
		_connect_recursively(child)

func _on_node_added(node: Node) -> void:
	if node is BaseButton:
		_connect_button(node)

func _connect_button(btn: BaseButton) -> void:
	#黑名单检查
	if btn.has_meta("no_sound"): return
	
	if not btn.has_meta("no_click_sound"):
		if not btn.pressed.is_connected(_play_click):
			btn.pressed.connect(_play_click)
	
	if not btn.has_meta("no_hover_sound"):
		if not btn.mouse_entered.is_connected(_play_hover):
			#使用.bind(btn)把按钮自己传给函数
			btn.mouse_entered.connect(_play_hover.bind(btn))

func _play_click() -> void:
	#print("播放点击音效")
	sfx_click.pitch_scale = randf_range(1, 1)
	sfx_click.play()

func _play_hover(btn: BaseButton) -> void:
	if btn.disabled:
		return
		
	sfx_hover.pitch_scale = randf_range(1, 1)
	sfx_hover.play()
